class Solution {
    vector<int> tmp;
    int ret = 0;
    void merge(vector<int> &nums, int left, int right)
    {
        if(left >= right)
            return;

        int mid = (left + right) >> 1;

        merge(nums, left, mid);
        merge(nums, mid + 1, right);

        // 到这里就有了两个有序数组，这道题我们是在合并两个有序数组之前统计翻转对的个数的
        int cur1 = left, cur2 = mid + 1;
        while(cur1 <= mid && cur2 <= right)
        {
            if(nums[cur1] / 2.0 > nums[cur2])
            {
                cur2++;
                ret += mid - cur1 + 1; 
            }
            else if(nums[cur1] / 2.0 <= nums[cur2])
                cur1++;
        }

        // 统计完翻转对之后再合并两个有序数组
        cur1 = left, cur2 = mid + 1;
        int i = 0;
        while(cur1 <= mid && cur2 <= right)
        {
            if(nums[cur1] <= nums[cur2])
                tmp[i++] = nums[cur1++];
            else
                tmp[i++] = nums[cur2++];
        }

        while(cur1 <= mid)
            tmp[i++] = nums[cur1++];

        while(cur2 <= right)
            tmp[i++] = nums[cur2++];

        for(int j = left; j <= right; j++)
            nums[j] = tmp[j - left];
    
    }
public:
    int reversePairs(vector<int>& nums) {
        int n = nums.size();
        tmp.resize(n);
        merge(nums, 0, n - 1);
        return ret;
    }
};